package com.adfframeworks.labs.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.adfframeworks.labs.dao.CommunityDAO;
import com.adfframeworks.labs.domain.Community;
import com.adfframeworks.labs.service.CommunityService;

@Service("communityService")
public class CommunityServiceImpl implements CommunityService {

	private CommunityDAO communityDAO;
	private TransactionTemplate txTemplate;

	@Autowired
	@Qualifier("communityDAOImpl")
	public void setCommunityDAO(CommunityDAO communityDAO) {
		this.communityDAO = communityDAO;
	}

	@Autowired
	public void setTxTemplate(TransactionTemplate txTemplate) {
		this.txTemplate = txTemplate;
	}

	@Override
	public void create(final String name, final Integer owner, final String keyword,
			final Integer visibility) {
		txTemplate.execute(new TransactionCallback<Void>() {
			public Void doInTransaction(TransactionStatus txStatus) {
				try {
					communityDAO.create(name, owner, keyword, visibility);
				} catch (RuntimeException e) {
					txStatus.setRollbackOnly();
					throw e;
				}
				return null;
			}
		});
	}

	@Override
	public Community getCommunity(Integer id) {
		return communityDAO.getCommunity(id);
	}

	@Override
	public Community getCommunity(String name) {
		return communityDAO.getCommunity(name);
	}

	@Override
	public List<Community> listTenLastCommunities() {
		return communityDAO.listTenLastCommunities();
	}

	@Override
	public List<Community> listAllCommunities() {
		return communityDAO.listAllCommunities();
	}

	@Override
	public List<Community> listKeywordCommunities(String keyword) {
		return communityDAO.listKeywordCommunities(keyword);
	}

	@Override
	public void delete(Integer id) {
		communityDAO.delete(id);
	}

	@Override
	public void delete(String name) {
		communityDAO.delete(name);
	}

	@Override
	public void update(Integer id, String name, Integer owner, String keyword,
			Integer visibility) {
		communityDAO.update(id, name, owner, keyword, visibility);
	}

}
